#include "mainwindow.h"
#include <QCoreApplication>
#include <QDir>
#include <QGuiApplication>
#include <QDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    /* 获取屏幕的分辨率，Qt官方建议使用这
     * 种方法获取屏幕分辨率，防上多屏设备导致对应不上
     * 注意，这是获取整个桌面系统的分辨率
     */
    QList <QScreen *> list_screen =  QGuiApplication::screens();

    /* 如果是ARM平台，直接设置大小为屏幕的大小 */
#if __arm__
    /* 重设大小 */
    this->resize(list_screen.at(0)->geometry().width(),
                 list_screen.at(0)->geometry().height());
    /* 默认是出厂系统的LED心跳的触发方式,想要控制LED，
     * 需要改变LED的触发方式，改为none，即无 */
    system("echo none > /sys/class/leds/sys-led/trigger");
#else
    /* 否则则设置主窗体大小为800x480 */
    this->resize(800, 480);
#endif

    musicLayout();

    mediaPlayerInit();

    scanSongs();

    connect(pushButton[0], &QPushButton::clicked,
            this, &MainWindow::btn_prev_clicked);
    connect(pushButton[1], &QPushButton::clicked,
            this, &MainWindow::btn_play_clicked);
    connect(pushButton[2], &QPushButton::clicked,
            this, &MainWindow::btn_next_clicked);

    connect(musicPlayer, &QMediaPlayer::stateChanged,
            this, &MainWindow::mediaPlayerStatusChanged);
    connect(musicPlayer, &QMediaPlayer::durationChanged,
            this, &MainWindow::musicPlayerDurationChanged);
    connect(musicPlayer, &QMediaPlayer::positionChanged,
            this, &MainWindow::mediaPlayerPositionChanged);

    connect(mediaPlaylist, &QMediaPlaylist::currentIndexChanged,
            this, &MainWindow::musicPlayerDurationChanged);

    connect(listWidget, &QListWidget::itemClicked,
            this, &MainWindow::listWidgetClicked);

    connect(durationSlider, &QSlider::sliderReleased,
            this, &MainWindow::duratiuonSliderReleased);

    this->setFocus();/* 失去焦点 */

    btn_play_clicked();
}

MainWindow::~MainWindow()
{

}

void MainWindow::musicLayout()
{
    QPalette pal;

    for (int i = 0; i < 7; i++) {
        pushButton[i] = new QPushButton();
    }

    for (int i = 0; i < 4; i++) {
        label[i] = new QLabel();
    }

    for (int i = 0; i < 3; i++) {
        vWidget[i] = new QWidget();
        vWidget[i]->setAutoFillBackground(true);
        vBoxLayout[i] = new QVBoxLayout();
        vWidget[i]->setLayout(vBoxLayout[i]);
    }

    for (int i = 0; i < 4; i++) {
        hWidget[i] = new QWidget();
        hWidget[i]->setAutoFillBackground(true);
        hBoxLayout[i] = new QHBoxLayout();
        hWidget[i]->setLayout(hBoxLayout[i]);
    }

    /* 播放进度条 */
    durationSlider = new QSlider(Qt::Horizontal);
    durationSlider->setMinimumSize(300, 15);
    durationSlider->setMaximumHeight(15);
    durationSlider->setObjectName("durationSlider");

    /* 音乐列表 */
    listWidget = new QListWidget();
    listWidget->setObjectName("listWidget");
    listWidget->resize(310, 265);
    listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    /* 列表遮罩 */
    listMask = new QWidget();
    listMask->setObjectName("listMask");
    listMask->setMinimumSize(310, 50);
    listMask->setMinimumHeight(50);
    listMask->setGeometry(0, listWidget->height() - 50, 310, 50);

    /* 设置对象名称 */
    pushButton[0]->setObjectName("btn_previous");
    pushButton[1]->setObjectName("btn_play");
    pushButton[2]->setObjectName("btn_next");
    pushButton[3]->setObjectName("btn_favorite");
    pushButton[4]->setObjectName("btn_mode");
    pushButton[5]->setObjectName("btn_menu");
    pushButton[6]->setObjectName("btn_volume");
    pushButton[1]->setCheckable(true);
    pushButton[3]->setCheckable(true);

    /* H0 布局 */
    vWidget[0]->setMinimumSize(310, 480);
    vWidget[0]->setMaximumWidth(310);
    vWidget[1]->setMinimumSize(320, 480);
    hBoxLayout[0]->addWidget(vWidget[0]);
    hBoxLayout[0]->addWidget(vWidget[1]);
    hBoxLayout[0]->setContentsMargins(0, 0, 0, 0);
    setCentralWidget(hWidget[0]);

    /* V0布局 */
    listWidget->setMinimumSize(310, 265);
    hWidget[1]->setMinimumSize(310, 80);
    hWidget[1]->setMaximumHeight(80);
    label[0]->setMinimumSize(310, 95);
    label[1]->setMaximumHeight(95);
    vBoxLayout[0]->addWidget(label[0]);
    vBoxLayout[0]->addWidget(listWidget);
    vBoxLayout[0]->addWidget(hWidget[1]);
    vBoxLayout[0]->setContentsMargins(0, 0, 0, 0);

    /* H1 布局 */
    pushButton[0]->setMinimumSize(80, 80);
    pushButton[1]->setMinimumSize(80, 80);
    pushButton[2]->setMinimumSize(80, 80);
    hBoxLayout[1]->addWidget(pushButton[0]);
    hBoxLayout[1]->addWidget(pushButton[1]);
    hBoxLayout[1]->addWidget(pushButton[2]);
    hBoxLayout[1]->setContentsMargins(0, 0, 0, 0);

    /* V1布局 */
    QImage image;
    image.load(":/images/cd.png");
    QPixmap pixmap = QPixmap::fromImage(image);
    int with = 320, height = 320;
    QPixmap fitpixmap = pixmap.scaled(with, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    label[1]->setPixmap(fitpixmap);
    label[1]->setAlignment(Qt::AlignCenter);
    label[1]->setMinimumSize(320, 320);
    vWidget[2]->setMinimumSize(300, 80);
    vWidget[2]->setMaximumHeight(80);
    vBoxLayout[1]->addWidget(label[1]);
    vBoxLayout[1]->addWidget(durationSlider);
    vBoxLayout[1]->addWidget(vWidget[2]);
    vBoxLayout[1]->setContentsMargins(0, 0, 0, 0);
    /* V2布局 */
    hWidget[2]->setMinimumSize(320, 20);
    hWidget[3]->setMinimumSize(320, 60);
    vBoxLayout[2]->addWidget(hWidget[2]);
    vBoxLayout[2]->addWidget(hWidget[3]);
    vBoxLayout[2]->setContentsMargins(0, 0, 0, 0);
    /* H2布局 */
    label[2]->setText("00:00");
    label[2]->setText("00:00");
    QFont font;
    font.setPixelSize(10);
    label[0]->setText("Q Music, Enjoy it!");
    label[2]->setText("00:00");
    label[3]->setText("00:00");
    label[2]->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    label[3]->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    label[2]->setAlignment(Qt::AlignLeft);
    label[3]->setAlignment(Qt::AlignRight);
    label[2]->setFont(font);
    label[3]->setFont(font);
    pal.setColor(QPalette::WindowText, Qt::white);
    label[0]->setPalette(pal);
    label[2]->setPalette(pal);
    label[3]->setPalette(pal);
    hBoxLayout[2]->addWidget(label[2]);
    hBoxLayout[2]->addWidget(label[3]);
    hBoxLayout[2]->setContentsMargins(0, 0, 0, 0);
    /* H3布局 */
    for (int i = 0; i < 7; i++) {
        pushButton[i]->setMinimumSize(25, 25);
        pushButton[i]->setMaximumSize(25, 25);
    }
    hBoxLayout[3]->addWidget(pushButton[3]);
    hBoxLayout[3]->addWidget(pushButton[4]);
    hBoxLayout[3]->addWidget(pushButton[5]);
    hBoxLayout[3]->addWidget(pushButton[6]);
    hBoxLayout[3]->setContentsMargins(0, 0, 0, 0);
    hBoxLayout[3]->setAlignment(Qt::AlignHCenter);
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);
    listMask->setGeometry(0, listWidget->height() - 50, 310, 50);
}

void MainWindow::scanSongs()
{
    /* 如果是ARM平台，直接设置大小为屏幕的大小 */
#if __arm__
    QDir dir(R"(/userdata/music)");
#else
    QDir dir(R"(D:\Desktop\myMusic)");
#endif

    QDir dirbsolutePath(dir.absolutePath());

    if (!dirbsolutePath.exists()) {
        qDebug() << dir << endl;
        return;
    }

    qDebug() << dir << endl;
    qDebug() << dirbsolutePath << endl;

    QStringList filter;
    filter << "*.mp3";
    QFileInfoList files = dirbsolutePath.entryInfoList(filter, QDir::Files);

    for(int i = 0; i < files.count(); i++) {
        QString filePath = files.at(i).filePath();
        if (mediaPlaylist->addMedia(QUrl::fromLocalFile(filePath))) {
            listWidget->addItem(files.at(i).fileName());
            qDebug() << "info.fileName" << filePath << endl;
        } else {
            qDebug() << "Error filePath" << filePath << endl;
            qDebug() << mediaPlaylist->errorString().toUtf8().data() << endl;
            qDebug() << "Error number:" << mediaPlaylist->error() << endl;
        }
    }
}

void MainWindow::mediaPlayerInit()
{
    musicPlayer = new QMediaPlayer(this);
    mediaPlaylist = new QMediaPlaylist(this);
    mediaPlaylist->clear();
    musicPlayer->setPlaylist(mediaPlaylist);
    mediaPlaylist->setPlaybackMode(QMediaPlaylist::Loop);
}

void MainWindow::btn_play_clicked()
{
    int state = musicPlayer->state();
    switch (state) {
    case QMediaPlayer::StoppedState: {
        musicPlayer->play();
    } break;
    case QMediaPlayer::PlayingState: {
        musicPlayer->pause();
    } break;
    case QMediaPlayer::PausedState: {
        musicPlayer->play();
    } break;
    }
}

void MainWindow::btn_next_clicked()
{
    musicPlayer->stop();
    int count = mediaPlaylist->mediaCount();
    if (count == 0)
        return;
    mediaPlaylist->next();
    musicPlayer->play();
}

void MainWindow::btn_prev_clicked()
{
    musicPlayer->stop();
    int count = mediaPlaylist->mediaCount();
    if (count == 0)
        return;
    mediaPlaylist->previous();
    musicPlayer->play();
}

void MainWindow::mediaPlayerStatusChanged(QMediaPlayer::State state)
{
    switch (state) {
    case QMediaPlayer::StoppedState: {
        pushButton[1]->setChecked(false);
    } break;
    case QMediaPlayer::PlayingState: {
        pushButton[1]->setChecked(true);
    } break;
    case QMediaPlayer::PausedState: {
        pushButton[1]->setChecked(false);
    } break;
    }
}

void MainWindow::listWidgetClicked(QListWidgetItem *item)
{
    musicPlayer->stop();
    mediaPlaylist->setCurrentIndex(listWidget->row(item));
    musicPlayer->play();
}

void MainWindow::mediaPlaylistCurrentIndexChanged(int index)
{
    if (index == -1)
        return;
    listWidget->setCurrentRow(index);
}

void MainWindow::musicPlayerDurationChanged(quint64 duration)
{
    durationSlider->setRange(0, static_cast<int>(duration / 1000));
    int second = static_cast<int>(duration / 1000);
    int minute = second / 60;
    second %= 60;

    QString mediaDuration;
    mediaDuration.clear();

    if (minute >= 10) {
        mediaDuration = QString::number(minute, 10);
    } else {
        mediaDuration = "0" + QString::number(minute, 10);
    }

    if (second >= 10) {
        mediaDuration += ":" + QString::number(second, 10);
    } else {
        mediaDuration += ":0" + QString::number(second, 10);
    }

    label[3]->setText(mediaDuration);/* 总长度 */
}

void MainWindow::mediaPlayerPositionChanged(quint64 position)
{
    if (!durationSlider->isSliderDown()) {
        durationSlider->setValue(static_cast<int>(position / 1000));
    }
    int second = static_cast<int>(position / 1000);
    int minute = second / 60;
    second %= 60;

    QString mediaPosition;
    mediaPosition.clear();

    if (minute >= 10) {
        mediaPosition = QString::number(minute, 10);
    } else {
        mediaPosition = "0" + QString::number(minute, 10);
    }

    if (second >= 10) {
        mediaPosition += ":" + QString::number(second, 10);
    } else {
        mediaPosition += ":0" + QString::number(second, 10);
    }

    label[3]->setText(mediaPosition); /* 现在播放时间 */
}

void MainWindow::duratiuonSliderReleased()
{
    musicPlayer->setPosition(durationSlider->value() * 1000);
}

